package com.threefish.common.utils;

import com.threefish.common.utils.http.HttpJsonResponse;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.List;

/**
 * @author 黄川 huchuc@vip.qq.com
 * @date: 2018/9/7
 */
public class HttpClientUtil {

    private static final String USER_AGENT = "Mozilla/5.0";

    private static final Logger log = LoggerFactory.getLogger(HttpClientUtil.class);


    public static HttpJsonResponse post(String postUrl, String charSet, List<NameValuePair> urlParameters) {
        HttpJsonResponse res = new HttpJsonResponse();
        try {
            HttpPost httppost = new HttpPost(postUrl);
            httppost.setEntity(new UrlEncodedFormEntity(urlParameters, charSet));
            return getHttpJsonResponse(httppost);
        } catch (Exception e) {
            log.error("错误", e);
            res.setErrormsg(e.getMessage() + "");
        }
        return res;
    }

    public static HttpJsonResponse get(String getUrl) {
        HttpJsonResponse res = new HttpJsonResponse();
        try {
            HttpGet httpGet = new HttpGet(getUrl);
            return getHttpJsonResponse(httpGet);
        } catch (Exception e) {
            log.error("错误", e);
            res.setErrormsg(e.getMessage() + "");
        }
        return res;
    }

    private static HttpJsonResponse getHttpJsonResponse(HttpRequestBase requestBase) throws IOException {
        HttpClient httpclient = HttpClients.createDefault();
        requestBase.setHeader("User-Agent", USER_AGENT);
        requestBase.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
        requestBase.setHeader("Accept-Encoding", "gzip, deflate");
        HttpResponse response = httpclient.execute(requestBase);
        HttpJsonResponse jsonResponse = new HttpJsonResponse();
        jsonResponse.setOk(false);
        jsonResponse.setStatusCode(response.getStatusLine().getStatusCode());
        final int httpSucessStatus = 200;
        if (response.getStatusLine().getStatusCode() == httpSucessStatus) {
            jsonResponse.setContent(IOUtils.toString(response.getEntity().getContent()));
            jsonResponse.setOk(true);
        } else {
            String error = response.getStatusLine().getStatusCode() + "错误！" + IOUtils.toString(response.getEntity().getContent());
            log.error(error);
            jsonResponse.setErrormsg(error);
        }
        return jsonResponse;
    }
}
